//
//  QZShopListController.m
//  WWShop
//
//  Created by 超群 on 15/10/14.
//  Copyright © 2015年 qunzhu.Team. All rights reserved.
//

#import "QZShopListController.h"
#import "QZShopListCell.h"
#import "MyButton.h"
#import "QZHairDetailViewController.h"

#import "QZShopInfoController.h"

#import "ListeView.h"
#import "QZShopModel.h"
#import "MJRefresh.h"

@interface QZShopListController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *mainView;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) MyButton *selectButton;

@property (nonatomic, strong) UITextField *searchBar;

@property (nonatomic, strong) UIView *gayView;

@property (nonatomic, strong) ListeView *shopListe;

@property (nonatomic, strong) NSMutableArray *shopArray;

@end

@implementation QZShopListController{
    
    NSString *_sort;//排序字段
    NSString *_sortSize;//排序大小
    NSInteger _page;//页数
}


-(NSMutableArray *)shopArray{
    if (_shopArray == nil) {
        _shopArray = [NSMutableArray array];
    }
    return _shopArray;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    //初始化这个参数，随便写的话，就获取所有列表
    _page = 1;
    self.navigationItem.title = @"商品列表";
    
    [self addBtnOnNavWithTitle:@"返回" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0, 45, 20) andDirection:left];

    //1341324343412441234
    [self createHeadView];
    
    [self createTableView];
    
    //创建NavigationBar 上的按钮
    [self prepreNvcButton];
    
    //创建蒙版，当点击搜索的时候有个蒙版，可以透明
    [self createGayView];
    
    [self createShopCategory];
    
    [self downloadDatas];
    
    [self addRefresh];
}

-(void)addRefresh{
    
    self.mainView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        _page = 1;
        [self downloadDatas];
        [self.mainView.header endRefreshing];
        
    }];
    
    self.mainView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page ++ ;
        [self downloadDatas];
        [self.mainView.footer endRefreshing];
        
    }];
    
}
-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)createHeadView{
    
    NSArray *array = @[@"价格",@"销量",@"上架时间"];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 30)];
    
    headView.backgroundColor = bgColor;
    CGFloat buttonW = (SCREEN_W)/3.0;
    CGFloat buttonH = headView.frame.size.height;
    
        for (int i = 0; i < 3 ; i ++ ) {
      __block  MyButton *button = [MyButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(i%3*(buttonW), 0, buttonW, buttonH) title:array[i] bgImage:nil image:nil selectedImage:nil block:^{
          //改变选择中状态
          _selectButton.selected = NO;
          _selectButton = button;
          _selectButton.selected = YES;
          
            NSLog(@"%@",array[i]);
          
          [self changeButton:i :button];
            
        }];
        [headView addSubview:button];
        
        [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
         [button setTitleColor:[UIColor colorWithRed:(180)/255.0f green:(90)/255.0f blue:(234)/255.0f alpha:1] forState:UIControlStateSelected];
            
        if (i == 0) {
            _selectButton = button;
            _selectButton.selected = YES;
        }
            button.backgroundColor = [UIColor whiteColor];
            button.layer.borderWidth =0.5;
            button.layer.borderColor = [UIColor colorWithRed:(240)/255.0f green:(240)/255.0f blue:(240)/255.0f alpha:1].CGColor;
            
            if (i == 0) {
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(buttonW/2.0+20, 7, 10, 17)];
                imageView.image = [UIImage imageNamed:@"箭头图标"];
                button.leftImageView = imageView;
            }

            

    }
  //  bgColor(180,90,234)
    
    
    _headView = headView;
    [self.view addSubview:_headView];

}


-(void)changeButton:(NSInteger)index :(MyButton *)button{
    static int pricNo;
    static int number;
    static int addtime;
    _page = 1;
    [self.shopArray removeAllObjects];
    
    switch (index) {
        case 0:{
            if (pricNo%2 == 0) {
                button.leftImageView.image = [UIImage imageNamed:@"箭头图标1"];
               
            }else{
                button.leftImageView.image = [UIImage imageNamed:@"箭头图标"];
                
            }
            [self changeImageView:pricNo :button];
            pricNo++;
            _sort = @"price2";
            [self downloadDatas];
            
        }break;
        case 1:{
            _sort = @"saleNum";
            [self changeImageView:number :button];
            number++;
            [self downloadDatas];
            
        }break;
        case 2:{
            _sort = @"addtime";
            [self changeImageView:addtime :button];
            addtime++;
            [self downloadDatas];
            
            
        }break;
            
        default:
            break;
    }
  
}
-(void)changeImageView:(NSInteger)index :(MyButton *)button{
    
    if (index%2 == 0) {
        _sortSize = @"left";
    }else{
        _sortSize = @"right";
    }
    
}

- (void)createTableView{
    self.view.backgroundColor = [UIColor whiteColor];
    _mainView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height-64-30) style:UITableViewStylePlain];
    _mainView.delegate = self;
    _mainView.dataSource =self;
    _mainView.separatorStyle = NO;


    [self.view addSubview:_mainView];
    
    
}
#pragma mark- tableView deletage
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.shopArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"QZShopListCellID";
    
    QZShopListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[QZShopListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.shopModel = self.shopArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
  
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    return _headView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    QZShopModel *model = self.shopArray[indexPath.row];
    QZShopInfoController *deta = [[QZShopInfoController alloc] initWithNibName:nil bundle:nil];
    deta.prodID = model.prodId;
    
    deta.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:deta animated:YES];
    
    
}
#pragma mark 隐藏 键盘
- (void)hideKeyboard:(UITapGestureRecognizer *)tap
{
    _gayView.hidden = YES;
    [_shopListe lisetViewHieddn];
    [self.searchBar resignFirstResponder];
}
#pragma mark 创建 navigationBar
-(void)prepreNvcButton{
//    //左边的item
//    UITapGestureRecognizer *tapLeft = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftClick:)];
//    
//    UIView *left = [[UIView alloc] initWithFrame:CGRectMake(0, 7, 60, 30)];
//
//    [left addGestureRecognizer:tapLeft];
//    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
//    lable.text = @"商品";
//    lable.textColor = [UIColor whiteColor];
//    [left addSubview:lable];
//    
//    UIImageView *view =[[UIImageView alloc] initWithFrame:CGRectMake(40, 10, 15, 10)];
//    view.image = [UIImage imageNamed:@"矩形-18"];
//    [left addSubview:view];
//    
//    UIBarButtonItem *itme =[[UIBarButtonItem alloc] initWithCustomView:left];
//    self.navigationItem.rightBarButtonItem =itme;
    
    
    //添加搜索框
    UIView *search = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W-10, 30)];
    
    search.layer.masksToBounds = YES;
    search.layer.cornerRadius = 15;
    
    search.backgroundColor = RGBACOLOR(255, 255, 255, 0.4);
    
    _searchBar = [[UITextField alloc] initWithFrame:CGRectMake(20, 0, SCREEN_W-20, 30)];
    _searchBar.placeholder = @"搜索商品";
    _searchBar.returnKeyType = UIReturnKeySearch;
    _searchBar.backgroundColor = [UIColor clearColor];
    _searchBar.delegate = self;
    
    [search addSubview:_searchBar];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchButtonClick:)];
    
    UIImageView *searchImage = [[UIImageView alloc] initWithFrame:CGRectMake(_searchBar.frame.size.width-85, 5, 20, 20)];
    searchImage.userInteractionEnabled = YES;
    [searchImage addGestureRecognizer:tap];
    searchImage.image = [UIImage imageNamed:@"查找"];
    [search addSubview:searchImage];
    
    [self.navigationItem setTitleView:search];
    
}

#pragma mark 搜索点击按钮
-(void)searchButtonClick:(UITapGestureRecognizer *)tap{
    _gayView.hidden = YES;
    _sort = nil;
    _sortSize = nil;

    [_shopListe lisetViewHieddn];
    [_searchBar resignFirstResponder];
    _page = 1;
    [self downloadDatas];
    
}

#pragma mark textField delegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    _gayView.hidden = NO;
    [_shopListe lisetViewHieddn];
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    _searchString = textField.text;
    [_shopListe lisetViewHieddn];
    [self searchButtonClick:nil];
    
    _gayView.hidden = YES;
    return YES;
}
-(void)leftClick:(UITapGestureRecognizer *)tap{
    static BOOL isSelect;
    if (!isSelect) {
        [_shopListe lisetViewShow];
        _gayView.hidden = NO;
        
    }else{
        [_shopListe lisetViewHieddn];
        _gayView.hidden = YES;
    }
    [_searchBar resignFirstResponder];
    isSelect = !isSelect;
    
    
}
-(void)createGayView{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard:)];
    
    _gayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64)];
    _gayView.hidden = YES;
    _gayView.backgroundColor = [UIColor blackColor];
    _gayView.alpha = 0.3;
    [_gayView addGestureRecognizer:tap];
    [self.view addSubview:_gayView];
}
-(void)createShopCategory{
    
    _shopListe = [[ListeView alloc] initWithFrame:CGRectMake(WIDTH-120,50, 100, 200)];
    
    [self.navigationController.tabBarController.view addSubview:_shopListe];
    
    _shopListe.frame = CGRectMake(WIDTH-120, 50, 100, 0);

}



#pragma mark 获取商品列表(搜索接口)
-(void)downloadDatas{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Prod.GetProdList"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];

        [dic setObject:@(_page) forKey:@"page"];
        [dic setObject:@(8) forKey:@"limit"];
        
        if (_searchString) {
            [dic setObject:_searchString forKey:@"search"];
        }
        if (_prod_cate_id) {
            [dic setObject:@(_prod_cate_id) forKey:@"prod_cate_id"];
        }
        if (_sort) {
            [dic setObject:_sort forKey:@"sort"];
        }
        if (_sortSize) {
            [dic setObject:_sortSize forKey:@"sort_type"];
        }
    

    NSLog(@"%@",dic);
    
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"商品列表" stopRequest:YES isSerializer:NO isCache:YES];
}

-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    if ([tag isEqualToString:@"商品列表"]) {
        if (_page == 1) {
            [self.shopArray removeAllObjects];
        }
        
        NSArray *data = value[@"data"][@"data"][@"list"];
        if ([value[@"data"][@"status"] integerValue] == 101) {
            
            [[iToast makeText:@"暂无商品"] show];
            return;
        }
        for (NSDictionary *dic in data) {
            QZShopModel *model = [[QZShopModel alloc] initWithDictionary:dic error:nil];
            [self.shopArray addObject:model];
        }
        [_mainView reloadData];
        
    }
}


@end
